using System.Threading.Tasks;
using System;
using System.IO;
using System.Text;
using UMC.Net;
using System.Net.WebSockets;

namespace UMC.ITME
{

    class HttpsWebSocket : UMC.Net.Mime, IDisposable
    {
        public override bool IsWebSocket => true;
        System.IO.Stream stream;
        System.Net.Sockets.Socket client;
        public HttpsWebSocket(HttpMime mime, System.Net.Sockets.Socket socket, System.IO.Stream stream) : base(mime.MimeMemory)
        {
            this.mime = mime;
            this.stream = stream;
            this.client = socket;
            WebSocketRead();
        }
        public override int Receive(byte[] buffer, int offset, int size)
        {
            stream.WriteAsync(buffer, offset, size);
            return 0;
        }
        bool _IsOver = false;
        public override bool IsOver => _IsOver;// base.IsOver;
        HttpMime mime;
        async void WebSocketRead()
        {
            int size = 0;

            byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(0x400);
            try
            {

                while ((size = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    mime.Write(buffer, 0, size);
                }
            }
            catch
            {
            }
            finally
            {

                System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
            }
            _IsOver = true;
            this.Dispose();
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            this.mime.Dispose();
            stream.Close();
            stream.Dispose();
            this.client.Close();
            this.client.Dispose();

        }
    }
}

